﻿using System;
using System.Collections;
using Sirenix.OdinInspector;
using UnityEngine;
using Random = UnityEngine.Random;

namespace Gp.Scripts.Utils {
    public static class MathExtend {
        public static int Round(this float f) {
            return Mathf.RoundToInt(f);
        }

        public static bool IsInRange(this IList l, int index) {
            if (l == null) return false;
            return index >= 0 && index < l.Count;
        }
    }


    public static class MathUtil {
        /// <summary>
        /// 随机概率
        /// </summary>
        /// <param name="probability">成功概率</param>
        /// <returns>是否成功</returns>
        public static bool Chance(float probability) {
            probability = Mathf.Clamp01(probability);
            return probability switch {
                >= 1 => true,
                <= 0 => false,
                _ => probability >= Random.value
            };
        }


        /// <summary>
        /// 提供整数的向上取证计算。当a + b 接近边界时勿用
        /// </summary>
        /// <returns></returns>
        public static int Ceil(int a, int b) {
            if (b == 0) return int.MaxValue;
            return (a + b - 1) / b;
        }


        public static int Min0(this int num) {
            return Math.Max(0, num);
        }



        public static float CalEulerAngle(this Transform source, Transform target) {
            var dot = Vector3.Dot(source.forward, (target.position - source.position).normalized);
            return Mathf.Acos(dot) * Mathf.Rad2Deg;
        } 
        
        
        /// <summary>
        /// 判断某目标是否处于扇形区域中
        /// </summary>
        public static bool IsInSectorRange(Transform source, Transform target, float angleRange, float distance) {
            // 判断距离
            var dir = target.position - source.position;
            if (dir.magnitude > distance) return false;
            var halfAngleRange = angleRange / 2;
                
                
                
            var dot = Vector3.Dot(source.forward, dir.normalized);
            float targetAngle =  Mathf.Acos(dot) * Mathf.Rad2Deg;
            return targetAngle > -halfAngleRange && targetAngle < halfAngleRange;
        }
    }
}